package registe_router_handle

import (
	"github.com/kataras/iris/v12"
	"goServer/models"
)

// return json model part
type Job struct {
	// 这是一个Job的json struct
	JobName      string `json:"jobname"`
	CompanyName  string `json:"companyname"`
	Sort         string `json:"sort"`
	Location     string `json:"location"`
	Target       string `json:"target"`
	Business     string `json:"business"`
	Salary       string `json:"salary"`
	Financing    string `json:"financing"`
	Teamsize     string `json:"teamsize"`
	LogoPath     string `json:"logopath"`
	BkPath       string `json:"bkpath"`
	Introduction string `json:"introduction"`
	Place        string `json:"place"`
	Scale        string `json:"scale"`
}
type Jobinfo struct {
	// 这是一个含有多个Job的json struct，第一个数据为Number，后面包含Number个Job
	//Number int   `json:"number"`
	Jobs []Job `json:"jobs"`
}

// init part
func Init_jobinfo() {
	// GET localhost:8080/jobinfo?keyword=xxx
	// 给定关键词，返回所有包含关键词的Job
	RouterHandles = append(RouterHandles, RouterHandle{
		Method: "GET",
		Router: "/jobinfo",
		Handler: func(ctx iris.Context) {
			// write a json to the response body, which have two keys, "username" and "password"

			// get keyword from request
			keyword := ctx.URLParam("keyword")

			res := jobsFindAll(keyword)

			ctx.ContentType("application/json")
			ctx.JSON(res)
		},
	})

}

// deal data part (return json model)
func jobsFindAll(keyword string) Jobinfo {
	// 放回一个Jobinfo，包含所有名字包含keyword的Job，如果keyword为空，则返回所有Job

	// get db
	db, err := models.GetDBOnly()
	if err != nil {
		panic(err)
	}

	// get all jobs：如果keyword为空，则返回所有Job，否则返回名字包含keyword的Job，Job中有来自models.Jobs和models.Companies的数据
	var jobinfo Jobinfo
	if keyword == "" {
		db.Raw("SELECT * FROM jobs,companies WHERE company_id = companies.id", "%"+keyword+"%").Scan(&jobinfo.Jobs)

	} else {
		//db.Where("job_name LIKE ?", "%"+keyword+"%").Find(&jobinfo.Jobs)
		db.Raw("SELECT * FROM jobs,companies WHERE job_name LIKE ? and company_id = companies.id", "%"+keyword+"%").Scan(&jobinfo.Jobs)
	}
	//jobinfo.Number = len(jobinfo.Jobs)

	return jobinfo
}
